<?php namespace Phpcmf\Home;

// 用于前端模块内容显示
class Module extends \Phpcmf\Common
{
    public $module; // 模块信息

    // 模块首页
    protected function _Index($html = 0) {

        // 初始化模块
        $this->_module_init();

        // 共享模块时禁止访问首页
        IS_SHARE && exit($this->goto_404_page(dr_lang('共享模块没有首页功能')));

        // 模板变量
        \Phpcmf\Service::V()->assign([
            'indexm' => 1,
            'markid' => 'module-'.MOD_DIR,
        ]);
        \Phpcmf\Service::V()->assign(\Phpcmf\Service::L('Seo')->module($this->module));


        \Phpcmf\Service::V()->display('index.html');
    }


    // 模块栏目页
    protected function _Category($catid = 0, $catdir = null, $page = 1) {

        if ($catid) {
            $category = $this->module['category'][$catid];
            if (!$category) {
                $this->goto_404_page(dr_lang('模块【%s】栏目（%s）不存在', MOD_DIR, $catid));
                return;
            }
        } elseif ($catdir) {
            $catid = intval($this->module['category_dir'][$catdir]);
            $category = $this->module['category'][$catid];
            if (!$category) {
                // 无法通过目录找到栏目时，尝试多及目录
                foreach ($this->module['category'] as $t) {
                    if ($t['setting']['urlrule']) {
                        $rule = \Phpcmf\Service::L('cache')->get('urlrule', $t['setting']['urlrule']);
                        $rule['value']['catjoin'] = '/';
                        if ($rule['value']['catjoin'] && strpos($catdir, $rule['value']['catjoin'])) {
                            $catdir = trim(strchr($catdir, $rule['value']['catjoin']), $rule['value']['catjoin']);
                            if (isset($this->module['category_dir'][$catdir])) {
                                $catid = $this->module['category_dir'][$catdir];
                                $category = $this->module['category'][$catid];
                                break;
                            }
                        }
                    }
                }
                // 返回无法找到栏目
                if (!$category) {
                    $this->goto_404_page(dr_lang('模块【%s】栏目（%s）不存在', MOD_DIR, $catdir));
                    return;
                }
            }
        } else {
            $this->goto_404_page(dr_lang('模块【%s】栏目不存在', MOD_DIR));
            return;
        }

        // 判断是否外链
        if ($category['tid'] == 2) {
            dr_redirect(dr_url_prefix($category['url']), 'refresh');exit;
        }

        // 单页验证是否存在子栏目，是否将下级第一个单页作为当前页
        if ($category['child'] && $category['setting']['getchild']) {
            $temp = explode(',', $category['childids']);
            if ($temp) {
                foreach ($temp as $i) {
                    if ($i != $catid && $this->module['category'][$i]['show'] && !$this->module['category'][$i]['child']) {
                        $catid = $i;
                        $category = $this->module['category'][$i];
                        // 初始化模块
                        $this->_module_init($category['mid'] ? $category['mid'] : 'share');
                        break;
                    }
                }
            }
        }



        // 获取同级栏目及父级栏目
        list($parent, $related) = dr_related_cat($this->module['category'], $catid);

        // 格式化字段
        $this->module['category_field']['content'] = [
            'name' => dr_lang('栏目内容'),
            'ismain' => 1,
            'fieldtype' => 'Ueditor',
            'fieldname' => 'content',
            'setting' => array(
                'option' => array(
                    'mode' => 1,
                    'height' => 300,
                    'width' => '100%'
                )
            ),
        ];

        $category = \Phpcmf\Service::L('Field')->format_value($this->module['category_field'], $category, $page);

        \Phpcmf\Service::V()->assign(\Phpcmf\Service::L('Seo')->category($this->module, $catid, $page));
        \Phpcmf\Service::V()->assign(array(
            'id' => $catid,
            'cat' => $category,
            'page' => $page,
            'catid' => $catid,
            'params' => ['catid' => $catid],
            'markid' => 'module-'.MOD_DIR.'-'.$catid,
            'parent' => $parent,
            'related' => $related,
            'urlrule' =>\Phpcmf\Service::L('Router')->category_url($this->module, $category, '[page]'),
        ));

        // 识别栏目单网页模板
        if (IS_SHARE && $category['tid'] == 0) {
            \Phpcmf\Service::V()->assign($category);
            \Phpcmf\Service::V()->assign(array(
                'pageid' => $catid,
            ));
            $tpl = !$category['setting']['template']['page'] ? 'page.html' : $category['setting']['template']['page'];
        } else {
            \Phpcmf\Service::V()->module(MOD_DIR);
            $tpl = $category['child'] ? $category['setting']['template']['category'] : $category['setting']['template']['list'];
        }
        \Phpcmf\Service::V()->display($tpl);
    }

    // 模块搜索
    protected function _Search($_catid = 0) {

        // 是否关闭
        (!isset($this->module['setting']['search']['use']) || !$this->module['setting']['search']['use'])
        && exit($this->_msg(0, dr_lang('此模块已经关闭了搜索功能')));

        // 无权限访问模块
        !dr_member_auth($this->member_authid, $this->member_cache['auth_module'][SITE_ID][MOD_DIR]['home'])
        && exit($this->_msg(0, dr_lang('您的用户组无权限搜索')));

        // 模型类
        $search = \Phpcmf\Service::M('Search', MOD_DIR)->init(MOD_DIR);

        // 搜索参数
        list($catid, $get) = $search->get_param($this->module);
        !$catid && $_catid && $catid = $_catid;
        $catid = intval($catid);

        // 关键字个数判断
        $get['keyword'] && strlen($get['keyword']) < (int)$this->module['setting']['search']['length']
        && exit($this->_msg(0, dr_lang('关键字不得少于系统规定的长度')));

        // 太长了
        strlen($get['keyword']) > 100 && exit($this->_msg(0, dr_lang('关键字太长了')));

        // 搜索数据
        $data = $search->get($this->module, $get, $catid);
        isset($data['code']) && $data['code'] == 0 && $data['msg'] && exit($this->_msg(0, $data['msg']));
        unset($data['params']['page']);

        // 获取同级栏目及父级栏目
        list($parent, $related) = dr_related_cat($this->module['category'], $catid);

        \Phpcmf\Service::V()->assign(\Phpcmf\Service::L('Seo')->search($this->module, $data['params'], $get['page']));
        \Phpcmf\Service::V()->assign(array(
            'cat' => $this->module['category'][$catid],
            'get' => $get,
            'catid' => $catid,
            'parent' => $parent,
            'params' => $data['params'],
            'keyword' => $data['keyword'],
            'related' => $related,
            'urlrule' => \Phpcmf\Service::L('Router')->search_url($data['params'], 'page', '{page}'),
            'sototal' => $data['contentid'] ? substr_count($data['contentid'], ',') + 1 : 0,
            'searchid' => $data['id'],
            'search_id' => $data['id'],
            'search_sql' => $data['sql'],
        ));
        \Phpcmf\Service::V()->module(MOD_DIR);

        // 挂钩点 搜索完成之后
        \Phpcmf\Hooks::trigger('module_search_data', $data);

        \Phpcmf\Service::V()->display($catid && $this->module['category'][$catid]['setting']['template']['search'] ? $this->module['category'][$catid]['setting']['template']['search'] : 'search.html');
    }

    // 模块内容页
    // $param 自定义字段检索
    protected function _Show($id = 0, $param = [], $page = 1, $rt = 0) {

        // 通过自定义字段查找id
        !$id && isset($param['field']) && $this->module['field'][$param['field']]['ismain'] && $id = $this->content_model->find_id($param['field'], $param['value']);

        $name = MOD_DIR.'_module_show_id_'.$id;
        $data = \Phpcmf\Service::L('cache')->init()->get($name);
        if (!$data) {
            $data = $this->content_model->get_data($id);
            if (!$data) {
                $this->goto_404_page(dr_lang('%s内容(#%s)不存在', $this->module['name'], $id));
                return;
            }

            // 检测转向字段
            foreach ($this->module['field'] as $t) {
                if ($t['fieldtype'] == 'Redirect' && $data[$t['fieldname']]) {
                    // 存在转向字段时的情况
                    \Phpcmf\Service::M()->db->table(SITE_ID.'_'.MOD_DIR)->where('id', $id)->set('hits', 'hits+1', FALSE)->update();
                    \Phpcmf\Service::V()->assign('gotu_url', $data[$t['fieldname']]);
                    \Phpcmf\Service::V()->display('go', 'admin');
                    return;
                }
            }

            // 处理关键字标签
            $data['tag'] = $data['keywords'];
            $data['tags'] = [];
            if ($data['keywords']) {
                $tag = explode(',', $data['keywords']);
                foreach ($tag as $t) {
                    $t = trim($t);
                    $t && $data['tags'][$t] = $this->content_model->get_tag_url($t);
                }
            }

            // 上一篇文章
            $builder = \Phpcmf\Service::M()->db->table($this->content_model->mytable);
            $builder->where('catid', (int)$data['catid'])->where('status', 9);
            $builder->where('id<', $id)->orderBy('id desc');
            $data['prev_page'] = $builder->limit(1)->get()->getRowArray();

            // 下一篇文章
            $builder = \Phpcmf\Service::M()->db->table($this->content_model->mytable);
            $builder->where('catid', (int)$data['catid'])->where('status', 9);
            $builder->where('id>', $id)->orderBy('id asc');
            $data['next_page'] = $builder->limit(1)->get()->getRowArray();

            // 格式化输出自定义字段
            $fields = $this->module['category'][$data['catid']]['field'] ? array_merge($this->module['field'], $this->module['category'][$data['catid']]['field']) : $this->module['field'];
            $fields['inputtime'] = ['fieldtype' => 'Date'];
            $fields['updatetime'] = ['fieldtype' => 'Date'];

            // 格式化字段
            $data = \Phpcmf\Service::L('Field')->format_value($fields, $data, $page);

            // 模块的回调处理
            $data = $this->_call_show($data);

            // 缓存结果
            $data['uid'] != $this->uid && \Phpcmf\Service::L('cache')->init()->save($name, $data, SYS_CACHE_SHOW * 3600);
        }

        // 挂钩点 内容读取之后
        \Phpcmf\Hooks::trigger('module_show_read_data', $data);

        // 状态判断
        if ($data['status'] == 10 && !($this->uid == $data['uid'] || $this->member['is_admin'])) {
            $this->goto_404_page(dr_lang('内容被删除，暂时无法访问'));
            return;
        }

        $catid = $data['catid'];


        // 判断是否同步栏目
        if ($data['link_id'] && $data['link_id'] > 0) {
            \Phpcmf\Service::V()->assign('gotu_url', dr_url_prefix($data['url']));
            \Phpcmf\Service::V()->display('go.html', 'admin');
            return;
        }

        // 判断分页
        if ($page && $data['content_page'] && !$data['content_page'][$page]) {
            $this->goto_404_page(dr_lang('该分页不存在'));
            return;
        }


        // 获取同级栏目及父级栏目
        list($parent, $related) = dr_related_cat($this->module['category'], $data['catid']);

        \Phpcmf\Service::V()->assign($data);
        \Phpcmf\Service::V()->assign(\Phpcmf\Service::L('Seo')->show($this->module, $data, $page));
        \Phpcmf\Service::V()->assign([
            'cat' => $this->module['category'][$data['catid']],
            'page' => $page,
            'params' => ['catid' => $catid],
            'parent' => $parent,
            'markid' => 'module-'.MOD_DIR.'-'.$catid,
            'related' => $related,
            'urlrule' =>\Phpcmf\Service::L('Router')->show_url($this->module, $data, '[page]'),
        ]);
        \Phpcmf\Service::V()->module(MOD_DIR);
        !$rt && (\Phpcmf\Service::V()->display(isset($data['template']) && strpos($data['template'], '.html') !== FALSE ? $data['template'] : ($this->module['category'][$data['catid']]['setting']['template']['show'] ? $this->module['category'][$data['catid']]['setting']['template']['show'] : 'show.html')));
        return $data;
    }

    // 模块草稿、审核、定时、内容页
    protected function _MyShow($type, $id = 0, $page = 1) {

        switch($type) {

            case 'time':
                $row = \Phpcmf\Service::M()->table(SITE_ID.'_'.MOD_DIR.'_time')->get($id);
                $data = dr_string2array($row['content']);
                !$data && $this->_msg(0, dr_lang('定时内容#%s不存在', $id));
                ($this->uid != $data['uid'] || !$this->member['is_admin']) && $this->_msg(0, dr_lang('定时内容只能自己访问'));
                break;

            case 'recycle':
                $row = \Phpcmf\Service::M()->table(SITE_ID.'_'.MOD_DIR.'_recycle')->get($id);
                $row = dr_string2array($row['content']);
                !$row && $this->_msg(0, dr_lang('回收站内容#%s不存在', $id));
                !$row[SITE_ID.'_'.MOD_DIR] && $this->_msg(0, dr_lang('回收站内容#%s格式不规范', $id));
                !$this->member['is_admin'] && $this->_msg(0, dr_lang('无权限访问'));
                $data = $row[SITE_ID.'_'.MOD_DIR];
                isset($row[SITE_ID.'_'.MOD_DIR.'_data_'.intval($data['tableid'])])
                && $row[SITE_ID.'_'.MOD_DIR.'_data_'.intval($data['tableid'])]
                && $data = array_merge($data, $row[SITE_ID.'_'.MOD_DIR.'_data_'.intval($data['tableid'])]);
                break;

            case 'verify':
                $row = \Phpcmf\Service::M()->table(SITE_ID.'_'.MOD_DIR.'_verify')->get($id);
                $data = dr_string2array($row['content']);
                !$data && $this->_msg(0, dr_lang('审核内容#%s不存在', $id));
                ($this->uid != $data['uid'] || !$this->member['is_admin']) && $this->_msg(0, dr_lang('无权限访问'));
                break;

            case 'draft':
                $row = \Phpcmf\Service::M()->table(SITE_ID.'_'.MOD_DIR.'_draft')->get($id);
                $data = dr_string2array($row['content']);
                !$data && $this->_msg(0, dr_lang('草稿内容#%s不存在', $id));
                ($this->uid != $data['uid'] || !$this->member['is_admin']) && $this->_msg(0, dr_lang('无权限访问'));
                break;

            default:
                $this->_msg(0, dr_lang('未定义的操作'));exit;
        }

        $data['id'] = 0;

        // 处理关键字标签
        $data['tag'] = $data['keywords'];
        $data['keyword_list'] = [];
        if ($data['keywords']) {
            $data['keywords'] = explode(',', $data['keywords']);
            foreach ($data['keywords'] as $t) {
                $t = trim($t);
                $t && $data['keyword_list'][$t] = $this->content_model->get_tag_url($t);
            }
        }

        // 格式化输出自定义字段
        $fields = $this->module['category'][$data['catid']]['field'] ? array_merge($this->module['field'], $this->module['category'][$data['catid']]['field']) : $this->module['field'];
        $fields['inputtime'] = ['fieldtype' => 'Date'];
        $fields['updatetime'] = ['fieldtype' => 'Date'];

        // 格式化字段
        $data = \Phpcmf\Service::L('Field')->app(MOD_DIR)->format_value($fields, $data, $page);

        // 判断分页
        if ($page && $data['content_page'] && !$data['content_page'][$page]) {
            $this->goto_404_page(dr_lang('该分页不存在'));
            return;
        }

        // 获取同级栏目及父级栏目
        list($parent, $related) = dr_related_cat($this->module['category'], $data['catid']);

        \Phpcmf\Service::V()->assign($data);
        \Phpcmf\Service::V()->assign(\Phpcmf\Service::L('Seo')->show($this->module, $data, $page));
        \Phpcmf\Service::V()->assign([
            'cat' => $this->module['category'][$data['catid']],
            'page' => $page,
            'params' => ['catid' => $data['catid']],
            'parent' => $parent,
            'markid' => 'module-'.MOD_DIR.'-'.$data['catid'],
            'related' => $related,
            'urlrule' =>\Phpcmf\Service::L('Router')->show_url($this->module, $data, '[page]'),
        ]);
        \Phpcmf\Service::V()->module(MOD_DIR);
        \Phpcmf\Service::V()->display(isset($data['template']) && strpos($data['template'], '.html') !== FALSE ? $data['template'] : ($this->module['category'][$data['catid']]['setting']['template']['show'] ? $this->module['category'][$data['catid']]['setting']['template']['show'] : 'show.html'));
        return $data;
    }


    // 前端模块回调处理类
    protected function _call_show($data) {

        return $data;
    }

}
